<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>当前时间</title>
  </head>
  <body>
    <div id="app">
      <!-- 当前时间 -->
      <div class="now-time">
        <h3>当前时间：{{ nowTime }}</h3>
      </div>
    </div>

    <script src="./lib/vue_v2.6.14.js"></script>
    <script>
      const app = new Vue({
        el: '#app',
        data: {
          nowTime: '',
          timer: 0
        },
        created() {
          this.getNowTime();
        },
        methods: {
          // 获取当前时间
          getNowTime() {
            // 清除定时器
            if (this.timer !== 0) clearInterval(this.timer);

            let dt = new Date();
            let year = dt.getFullYear();
            let month = dt.getMonth() + 1;
            month = month < 10 ? '0' + month : month;
            let day = dt.getDate();
            day = day < 10 ? '0' + day : day;
            const weeks = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
            let week = dt.getDay();

            let hour = dt.getHours();
            hour = hour < 10 ? '0' + hour : hour;
            let min = dt.getMinutes();
            min = min < 10 ? '0' + min : min;
            let sec = dt.getSeconds();
            sec = sec < 10 ? '0' + sec : sec;

            this.nowTime = `${year}-${month}-${day} ${weeks[week]} ${hour}:${min}:${sec}`;

            this.startTime();
          },

          // 启动定时器
          startTime() {
            this.timer = setInterval(() => {
              this.getNowTime();
            }, 1000);
          }
        }
      });
    </script>
  </body>
</html>
